//
//  NewMissonListController.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2018/4/2.
//  Copyright © 2018年 zjhcsoftios. All rights reserved.
//

#import "NewMissonListController.h"
#import <MJExtension/MJExtension.h>
#import "NewMissionListDetailModel.h"
#import "NewMissionListCell.h"
#import "MJRefresh.h"
#import "ZSBWorkOrdorSearchListView.h"
#import "ZSBRemindHeaderView.h"
#import <Masonry/Masonry.h>
#import "NewMissionListTimeFilterCell.h"
#import "NewLoveMarketTimeFilterView.h"
#import "ZSBWordOrdorSearchConditionView.h"
#import "MissionWebMask.h"
#import "UIViewController+GetBundle.h"
#import "UIColor+Ex.h"
#import "NetworkAddress.h"
#import "iSeeNetworkRequest.h"
#import "SVProgressHUD.h"
#import "NewMarketWebViewController.h"
#import "ISeeUserInfoModel.h"
//#import "NewOrdorListViewController.h"
#import "ZPHCNewReassignPeopleListViewController.h"
#import "NewMissonListDetailController.h"
#import "NSBundle+AssociatedBundle.h"

#define iSEESCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define iSEESCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface NewMissonListController ()<UITableViewDelegate,UITableViewDataSource,NewMissionListCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *selectButton;
@property (weak, nonatomic) IBOutlet UILabel *acceptOrdor;
@property (weak, nonatomic) IBOutlet UILabel *acceptProject;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomViewHeight;
@property (weak, nonatomic) IBOutlet UIView *buttomView;


@property (nonatomic, strong) NSMutableArray *dataList;

@property (nonatomic, strong) NSMutableArray *selectedArray;

//用于搜索功能
@property (nonatomic, strong) ZSBWorkSearchListModel *searchModel;
@property (nonatomic, strong) NSMutableDictionary *searchSuccessDic;

//批次选择按钮
@property (nonatomic, strong) NSString *batchSelection;
@property (nonatomic, strong) NSNumber *batchSelectionId;

@property (nonatomic, strong)UILabel *label;

@property (nonatomic, assign) NSInteger grobCountMax;
@property (nonatomic, assign) NSInteger grobed;
@property (nonatomic, assign) NSInteger canGrob;
@property (nonatomic, strong) ZSBRemindHeaderView *remind;

//搜索框显示和隐藏
@property (nonatomic, assign)BOOL searchshow;
//排序数据储存
@property (nonatomic, strong) ZSBSearchModel *sortModel;
@property (nonatomic, strong) ZSBSearchModel *upDownModel;

//是否显示待接单提示
@property (nonatomic, assign) BOOL showWaitingRemark;
//limitSize 待接单提示上限
@property (nonatomic, assign) NSInteger waitingLimitSize;
//remanentCount  待接单提示剩余可接单
@property (nonatomic, assign) NSInteger waitingRemanentCount;
//transitCount 待接单提示已有
@property (nonatomic, assign) NSInteger waitingTransitCount;

@end

@implementation NewMissonListController

static NSString *newMissionListCellIdentify = @"newMissionListCellIdentify";
static NSString *newMissionListBatchCellIdentify = @"newMissionListBatchCellIdentify";
static NSString *newMissionListTimeFilterCellIdentify = @"newMissionListTimeFilterCellIdentify";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataList = [NSMutableArray array];
    _selectedArray = [NSMutableArray array];
    _searchSuccessDic = [NSMutableDictionary dictionary];
    
    [_tableView registerClass:[NewMissionListCell class] forCellReuseIdentifier:newMissionListCellIdentify];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:newMissionListBatchCellIdentify];
    [_tableView registerNib:[self getNibFromBundle:@"NewMissionListTimeFilterCell"] forCellReuseIdentifier:newMissionListTimeFilterCellIdentify];
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 95;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.backgroundColor = [UIColor colorWithHexString:@"EAECEF"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getNewList];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getMoreList];
    }];
    
    
    [self setAcceptOrdorAndAcceptProject];
    
    self.showWaitingRemark = NO;
    
    [self.tableView.mj_header beginRefreshing];
    
    [self getSearchHeadModel];
    
    
    UIButton *searchBtnView = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtnView.tag = 2;
    searchBtnView.frame = CGRectMake(0, 0, 24, 24);
    [searchBtnView setBackgroundImage:[self getImageFromBundle: @"toolbar_btn_search"] forState:UIControlStateNormal];
    [searchBtnView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtnView addTarget:self action:@selector(searchButtonOnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchBtn = [[UIBarButtonItem alloc] initWithCustomView:searchBtnView];
    self.navigationItem.rightBarButtonItem =searchBtn;

    _batchSelection = @"批次选择";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relaodList) name:@"RELOADNEWMISSONLIST" object:nil];
    
}

- (void)relaodList {
    [self.tableView.mj_header beginRefreshing];
}


-(void)searchButtonOnClick:(UIButton *) button{
    
    button.userInteractionEnabled = NO;
    
    [ZSBWorkOrdorSearchListView showSearchPickerInView:self.view model:_searchModel success:^(NSDictionary *successDic) {
        if ([self.searchSuccessDic objectForKey:@"searchCol"]) {
            [self.searchSuccessDic removeObjectForKey:@"searchCol"];
        }
        [self.searchSuccessDic addEntriesFromDictionary:successDic];
        [self.tableView.mj_header beginRefreshing];;
        button.userInteractionEnabled = YES;
    } failure:^{
        button.userInteractionEnabled = YES;
    }];

    
}

- (void)setAcceptOrdorAndAcceptProject {
    _acceptOrdor.layer.masksToBounds = YES;
    _acceptOrdor.layer.cornerRadius = 2;
    
    _acceptProject.layer.masksToBounds = YES;
    _acceptProject.layer.cornerRadius = 2;
    _acceptProject.layer.borderWidth = 1;
    _acceptProject.layer.borderColor = [UIColor colorWithHexString:@"169BD5"].CGColor;
    
    //处理中状态
    if ([self.logId isEqualToString:@"521"]||[self.logId isEqualToString:@"528"]||[self.logId isEqualToString:@"529"]||[self.logId isEqualToString:@"542"])  {

        _acceptOrdor.hidden = YES;
            
        _acceptProject.text = @"批量转派";
        UITapGestureRecognizer *projectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(batchTransfer:)];
        [_acceptProject addGestureRecognizer:projectTap];

        
    }else if ([_logId isEqualToString:@"539"]) {
        
        _acceptOrdor.hidden = YES;
        
        _acceptProject.text = @"批量撤单";
        UITapGestureRecognizer *projectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(batchCannelOrdors:)];
        [_acceptProject addGestureRecognizer:projectTap];
        
    }else if ([_logId isEqualToString:@"544"]) {
        
        _acceptOrdor.hidden = YES;
        
        _acceptProject.text = @"批量派单";
        UITapGestureRecognizer *projectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(batchDispatchOredors)];
        [_acceptProject addGestureRecognizer:projectTap];
        
    }else if ([_logId isEqualToString:@"548"] || [_logId isEqualToString:@"526"]) {
        
        _acceptOrdor.hidden = YES;
        
        _acceptProject.text = @"批量抢单";
        UITapGestureRecognizer *projectTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(grabWorkOrdor:)];
        [_acceptProject addGestureRecognizer:projectTap];
        
    }else {
        self.buttomViewHeight.constant = 0;
        self.buttomView.hidden = YES;
        [self.view layoutIfNeeded];
    }
    
    
    if ([self.type isEqualToString:@"1"]) {
        self.buttomViewHeight.constant = 0;
        self.buttomView.hidden = YES;
        [self.view layoutIfNeeded];
    }
}

#pragma mark 数据处理

- (NSString *)getAllSelectedIds {
    NSString *string = @"";
    for (NewMissionListDetailModel *info in _selectedArray) {
        string = [NSString stringWithFormat:@"%@,%@",string,info.orderId];
    }
    if (string.length>0) {
        string = [string substringWithRange:NSMakeRange(1, string.length-1)];
    }
    return string;
}


#pragma mark 网络请求
- (void)getNewList {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    [params setObject:self.projectId forKey:@"projectId"];
    [params setObject:@(50) forKey:@"rows"];
    [params setObject:@(1) forKey:@"page"];
    
    //日期选择
    if (_startdate.length) {
        [params setObject:_startdate forKey:@"startDate"];
    }
    if (_enddate.length) {
        [params setObject:_enddate forKey:@"endDate"];
    }
    
    if (_sortModel && _upDownModel) {
        if ([_searchSuccessDic objectForKey:@"orderCol"]) {
            [_searchSuccessDic removeObjectForKey:@"orderCol"];
        }
        NSDictionary *ordorDic = [NSDictionary dictionaryWithObjectsAndKeys:_sortModel.value, @"name", _upDownModel.value, @"way", _sortModel.orderType, @"valueType", nil];
        
        [_searchSuccessDic addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:ordorDic], @"orderCol", nil]];
        
    }
    
    if (_searchSuccessDic.count > 0) {
        [params addEntriesFromDictionary:_searchSuccessDic];
    }
    
    if (![_batchSelection isEqualToString:@"批次选择"] && _batchSelectionId) {
        [params setObject:_batchSelectionId forKey:@"pcId"];
    }
    if (_timeFilterDic.count > 0) {
        [params setValuesForKeysWithDictionary:_timeFilterDic];
    }
    
    if ([self.type isEqualToString:@"1"]) {
        [params setObject:self.labelId forKey:@"labelId"];
        
        if (_key.length > 0) {
            [params setObject:self.key forKey:@"keywords"];
        }
        
        [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, GetOrderPageForTag] params:params success:^(id object) {
            [self.dataList removeAllObjects];
            [self.selectedArray removeAllObjects];
            NSDictionary *body = object[@"body"];
            NSArray *result = body[@"result"];
            
            [self.dataList addObjectsFromArray:[NewMissionListDetailModel mj_objectArrayWithKeyValuesArray:result]];
            self.projectId = object[@"body"][@"projectId"];
            self.grobCountMax = [object[@"body"][@"qdTotal"] integerValue];
            self.grobed = [object[@"body"][@"qdCount"] integerValue];
            self.canGrob = self.grobCountMax - self.grobed;
            [self.tableView reloadData];
            [self setSelectButtomStatus];
            [self.tableView.mj_header endRefreshing];
        } failure:^(NSError *error) {
            [self.tableView.mj_header endRefreshing];
        }];

        
    }else {
        
        [params setObject:self.logId forKey:@"logId"];
        if (self.key.length > 0) {
            [params setObject:self.key forKey:@"key"];
        }
        
        [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, GetOrderPage] params:params success:^(id object) {
            [self.dataList removeAllObjects];
            [self.selectedArray removeAllObjects];
            NSDictionary *body = object[@"body"];
            NSArray *result = body[@"result"];
            
            [self.dataList addObjectsFromArray:[NewMissionListDetailModel mj_objectArrayWithKeyValuesArray:result]];
            self.projectId = object[@"body"][@"projectId"];
            self.grobCountMax = [object[@"body"][@"qdTotal"] integerValue];
            self.grobed = [object[@"body"][@"qdCount"] integerValue];
            self.canGrob = self.grobCountMax - self.grobed;
            [self.tableView reloadData];
            [self setSelectButtomStatus];
            [self.tableView.mj_header endRefreshing];
        } failure:^(NSError *error) {
            [self.tableView.mj_header endRefreshing];
        }];
    }
    
    
    
    
    
}

- (void)getMoreList {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.projectId forKey:@"projectId"];
    [params setObject:@(50) forKey:@"rows"];
    if (self.dataList.count % 50) {
        NSInteger page = self.dataList.count/50 +1 +1;
        [params setObject:@(page) forKey:@"page"];
    }else{
        NSInteger page = self.dataList.count/50 + 1;
        [params setObject:@(page) forKey:@"page"];
    }
    
    if (![self.batchSelection isEqualToString:@"批次选择"] && self.batchSelectionId) {
        [params setObject:self.batchSelectionId forKey:@"pcId"];
    }
    //日期选择
    if (self.startdate.length) {
        [params setObject:self.startdate forKey:@"startDate"];
    }
    if (self.enddate.length) {
        [params setObject:self.enddate forKey:@"endDate"];
    }
    
    if (self.searchSuccessDic.count > 0) {
        [params addEntriesFromDictionary:self.searchSuccessDic];
    }
    
    if (self.timeFilterDic.count > 0) {
        [params setValuesForKeysWithDictionary:self.timeFilterDic];
    }
    
    if ([self.type isEqualToString:@"1"]) {
        [params setObject:self.labelId forKey:@"labelId"];
        if (self.key.length > 0) {
            [params setObject:self.key forKey:@"keywords"];
        }
        
        [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, GetOrderPageForTag] params:params success:^(id object) {
            NSDictionary *body = object[@"body"];
            NSArray *result = body[@"result"];
            
            NSArray *temp = [NewMissionListDetailModel mj_objectArrayWithKeyValuesArray:result];
            [self.dataList addObjectsFromArray:temp];
            self.projectId = object[@"body"][@"projectId"];
            self.grobCountMax = [object[@"body"][@"qdTotal"] integerValue];
            self.grobed = [object[@"body"][@"qdCount"] integerValue];
            self.canGrob = self.grobCountMax - self.grobed;
            
            [self.tableView reloadData];
            [self setSelectButtomStatus];
            [self.tableView.mj_footer endRefreshing];
        } failure:^(NSError *error) {
            [self.tableView.mj_footer endRefreshing];
        }];
        
    }else {
        
        [params setObject:self.logId forKey:@"logId"];
        if (self.key.length > 0) {
            [params setObject:self.key forKey:@"key"];
        }
        
        [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, GetOrderPage] params:params success:^(id object) {
            NSDictionary *body = object[@"body"];
            NSArray *result = body[@"result"];
            
            NSArray *temp = [NewMissionListDetailModel mj_objectArrayWithKeyValuesArray:result];
            [self.dataList addObjectsFromArray:temp];
            self.projectId = object[@"body"][@"projectId"];
            self.grobCountMax = [object[@"body"][@"qdTotal"] integerValue];
            self.grobed = [object[@"body"][@"qdCount"] integerValue];
            self.canGrob = self.grobCountMax - self.grobed;
            
            [self.tableView reloadData];
            [self setSelectButtomStatus];
            [self.tableView.mj_footer endRefreshing];
        } failure:^(NSError *error) {
            [self.tableView.mj_footer endRefreshing];
        }];
    }
}


- (void)getSearchHeadModel {
    
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    [parma setObject:self.projectId forKey:@"projectId"];
    
    
    [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, GetOrederTopSearchList] params:parma success:^(id object) {
        self.searchModel = [ZSBWorkSearchListModel mj_objectWithKeyValues:object[@"body"]];
        self.upDownModel = self.searchModel.order.data[0];
        if (self.searchModel.orderName.data.count > 0) {
            self.sortModel = self.searchModel.orderName.data[0];
        }
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return  2;
    }else {
        return self.dataList.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:newMissionListBatchCellIdentify forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = self.batchSelection;
            cell.textLabel.textColor = [UIColor colorWithHexString:@"444444"];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }else {
            
            //时间选择Cell
            NewMissionListTimeFilterCell *cell = [tableView dequeueReusableCellWithIdentifier:newMissionListTimeFilterCellIdentify forIndexPath:indexPath];
            
            UITapGestureRecognizer *filterTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tiemFilterViewAction:)];
            [cell.timeFilterView addGestureRecognizer:filterTap];
            
            UITapGestureRecognizer *sortTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sortViewAction:)];
            [cell.sortView addGestureRecognizer:sortTap];
            
            [cell.upDownButton addTarget:self action:@selector(updownButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            if (self.sortModel) {
                cell.sortLabel.text = self.sortModel.name;
            }
            
            if (self.upDownModel) {
                [cell.upDownButton setImage:[self getImageFromBundle:self.upDownModel.name] forState:UIControlStateNormal];
            }
            
            return cell;
        }
    }else {
        
        NewMissionListCell *cell = [tableView dequeueReusableCellWithIdentifier:newMissionListCellIdentify forIndexPath:indexPath];
        cell.model  = self.dataList[indexPath.row];
        cell.delegate = self;
        if (indexPath.row == self.dataList.count - 1) {
            cell.isLastCell = YES;
        }else {
            cell.isLastCell = NO;
        }
        return cell;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        if ([self.logId isEqualToString:@"548"]) {
            return 30;
        }
        if ([self.logId isEqualToString:@"537"] || [self.logId isEqualToString:@"538"] || [self.logId isEqualToString:@"520"]) {
            if (self.showWaitingRemark) {
                return 30;
            }else {
                return 0;
            }
        }
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        
        return 10;
    }else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *foot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, iSEESCREEN_WIDTH, 10)];
    foot.backgroundColor = [UIColor colorWithHexString:@"EAECEF"];
    
    return foot;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 1 ) {
        
        if ([self.logId isEqualToString:@"548"]) {
            
            UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 40)];
            headerView.backgroundColor = [UIColor whiteColor];
            if (!self.remind) {
                self.remind = [[self getBundle] loadNibNamed:@"ZSBRemindHeaderView" owner:self options:nil].lastObject;
                self.remind.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, 30);
                headerView.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, 30);
                [headerView addSubview:self.remind];
                self.remind.headerLabel.text = [NSString stringWithFormat:@"抢单总数为%ld单，已抢%ld单，剩余%ld单；【接单并转派】不受限制", (long)self.grobCountMax,(long)self.grobed, (long)self.canGrob];
            }else {
                headerView.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, 30);
                [headerView addSubview:self.remind];
                self.remind.headerLabel.text = [NSString stringWithFormat:@"抢单总数为%ld单，已抢%ld单，剩余%ld单", (long)self.grobCountMax,(long)self.grobed, (long)self.canGrob];
            }
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, headerView.bounds.size.height-0.5, headerView.bounds.size.width, 0.5)];
            line.backgroundColor = [UIColor colorWithHexString:@"EAECEF"];
            [headerView addSubview:line];
            return headerView;
        }
        if ([self.logId isEqualToString:@"537"] || [self.logId isEqualToString:@"538"] || [self.logId isEqualToString:@"520"]) {
            if (self.showWaitingRemark) {
                UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 40)];
                headerView.backgroundColor = [UIColor whiteColor];
                if (!self.remind) {
                    self.remind = [[self getBundle] loadNibNamed:@"ZSBRemindHeaderView" owner:self options:nil].lastObject;
                    self.remind.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, 30);
                    headerView.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, 30);
                    [headerView addSubview:self.remind];
                    self.remind.headerLabel.text = [NSString stringWithFormat:@"当前工号工单上限：%ld 单 ； 当前已接：%ld 单；剩余可接：%ld 单；【接单并转派】不受限制", (long)self.waitingLimitSize,(long)self.waitingTransitCount, (long)self.waitingRemanentCount];
                    //            _label.frame = CGRectMake(15, 35, 100, 30);
                }else {
                    headerView.frame = CGRectMake(0, 0, iSEESCREEN_WIDTH, 30);
                    [headerView addSubview:self.remind];
                    self.remind.headerLabel.text = [NSString stringWithFormat:@"当前工号工单上限：%ld 单 ； 当前已接：%ld 单；剩余可接：%ld 单；【接单并转派】不受限制", (long)self.waitingLimitSize,(long)self.waitingTransitCount, (long)self.waitingRemanentCount];
                    //            _label.frame = CGRectMake(15, 35, 100, 30);
                }
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, headerView.bounds.size.height-0.5, headerView.bounds.size.width, 0.5)];
                line.backgroundColor = [UIColor colorWithHexString:@"EAECEF"];
                [headerView addSubview:line];
                return headerView;
            }
        }
        

        return [[UIView alloc] init];
    }else {
        
        return [[UIView alloc] init];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self batchSelectionCellAction];
        }else {
            
        }
    }else {
        NewMissionListDetailModel *model = self.dataList[indexPath.row];
        ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
        
        if (userInfo.marketVersion == 0) {
            NewMissonListDetailController *ctrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] instantiateViewControllerWithIdentifier:@"NewMissonListDetailController"];
            ctrl.ordorId = model.orderId;
            ctrl.isOrdorListEnter = NO;
            ctrl.logId = model.logId;
            [self.navigationController pushViewController:ctrl animated:YES];
            
        }else if (userInfo.marketVersion == 2) {
            
            NewMarketWebViewController *detail = [[NewMarketWebViewController alloc] init];
            detail.loadUrl = [NSString stringWithFormat:@"%@hmarket/#/workorder-detail?orderId=%@&session=%@&userId=%@", NMarketMainUrl, model.orderId, [[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserSession], userInfo.userId];
            [self.navigationController pushViewController:detail animated:YES];
        }
        
    }
    
}

#pragma mark cell选择取消方法
- (void)NewMissionListCellSelectButtonAction:(NewMissionListDetailModel *)model {
    
    
    if (model.isSelect) {
        
        [self.selectedArray addObject:model];
        
    }else {
        
        [self.selectedArray removeObject:model];
        
    }
    [self setSelectButtomStatus];
}

//全选按钮状态
- (void)setSelectButtomStatus {
    if (self.dataList.count == self.selectedArray.count && self.dataList.count != 0) {
        
        self.selectButton.selected = YES;
        [self.selectButton setTitle:[NSString stringWithFormat:@"取消全选(已选%lu)", (unsigned long)self.selectedArray.count] forState:UIControlStateSelected];
    }else {
        
        self.selectButton.selected = NO;
        [self.selectButton setTitle:[NSString stringWithFormat:@"全选(已选%lu)", (unsigned long)self.selectedArray.count] forState:UIControlStateNormal];
    }
    [self.selectButton layoutIfNeeded];
}

#pragma mark 按钮点击事件

//批量接单并转派
- (void)batchWaitingReceivingOrdorAndTransfer:(UITapGestureRecognizer *)tap {
    if (self.selectedArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }
    ZPHCNewReassignPeopleListViewController * viewCtrl = [[ZPHCNewReassignPeopleListViewController alloc] initWithIsPZ:NO];
    viewCtrl.billIds = [self getAllSelectedIds];
    for (NewMissionListDetailModel *info in self.selectedArray) {

        viewCtrl.zpRemarkFlag = info.zpRemarkFlag;

    }
    viewCtrl.zpHdImageFlag = @"2";
    viewCtrl.isReceiveAndTransfer = YES;
    [self.navigationController pushViewController:viewCtrl animated:YES];
}


//批量转派
- (void)acceptProjectAction:(UITapGestureRecognizer *) tap {
    if (self.selectedArray.count == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }
    
    ZPHCNewReassignPeopleListViewController * viewCtrl = [[ZPHCNewReassignPeopleListViewController alloc] init];
    viewCtrl.billIds = [self getAllSelectedIds];
    [self.navigationController pushViewController:viewCtrl animated:YES];
}

//批量回单
- (void)batchReceipt:(UITapGestureRecognizer *)tap
{
    if (self.selectedArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    __weak NewMissonListController *wself = self;
    [MissionWebMask showReceiptView:window isReceipt:YES detailIds:[self getAllSelectedIds] phoneNum:nil url:nil success:^(NSString *successStr) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"回单成功" message:@"请选择转跳页面" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"工单首页" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wself.navigationController popToRootViewControllerAnimated:YES];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"工单列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.tableView.mj_header beginRefreshing];
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    } failure:^{
        
    }];

}

//批量转派
- (void)batchTransfer:(UITapGestureRecognizer *)tap {
    if (self.selectedArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }

}

//待接单状态 批量接单
- (void)waitingReceivingOrdors:(UITapGestureRecognizer *)tap {
    
    if (self.selectedArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[self getAllSelectedIds] forKey:@"orderIds"];
    [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, BatchOrderListAcceptAndReject] params:params success:^(id object) {
        [self.tableView.mj_header beginRefreshing];;
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"操作成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"去处理" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.logId = @"528";
            self.title = @"未联系";
            [self setAcceptOrdorAndAcceptProject];
            [self.tableView.mj_header beginRefreshing];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"留在原地" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.userInfo[@"msg"]];
        
    }];

}

//批量撤单
- (void)batchCannelOrdors:(UITapGestureRecognizer *) tap {
    
    if (self.selectedArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[self getAllSelectedIds] forKey:@"orderIds"];
    if (self.logId.length) {
        [params setObject:self.logId forKey:@"logId"];
    }
    
    [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, BatchCannelOrder] params:params success:^(id object) {
            [SVProgressHUD showSuccessWithStatus:@"撤单成功"];
            [self.tableView.mj_header beginRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.userInfo[@"msg"]];
    }];

}

//批量派单
- (void)batchDispatchOredors {
    
    if (self.selectedArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择工单"];
        return;
    }

}

//抢单池组
- (void)grabWorkOrdor:(UITapGestureRecognizer *) tap {
    if ([_logId isEqualToString:@"548"]) {
        // 50条上线区分
        if (_selectedArray.count > _canGrob ) {
            [SVProgressHUD showErrorWithStatus:@"抢单超过上限"];
        }else {
            
            
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:_projectId forKey:@"projectId"];
            [params setObject:_logId forKey:@"logId"];
            [params setObject:[self getAllSelectedIds] forKey:@"orderIds"];
            [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, RobOrderFromOrderPool] params:params success:^(id object) {
                [SVProgressHUD showSuccessWithStatus:@"抢单成功"];
                [self.tableView.mj_header beginRefreshing];
            } failure:^(NSError *error) {
                 [SVProgressHUD showErrorWithStatus:@"抢单失败"];
            }];

        }
    }else {
            
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:_projectId forKey:@"projectId"];
        [params setObject:_logId forKey:@"logId"];
        [params setObject:[self getAllSelectedIds] forKey:@"orderIds"];
        
        [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, RobOrderFromOrderPool] params:params success:^(id object) {
            [SVProgressHUD showSuccessWithStatus:@"抢单成功"];
            [self.tableView.mj_header beginRefreshing];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"抢单失败"];
        }];

    }
    
    
}

//批次选择点击按钮
-(void)batchSelectionCellAction {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if ([self.type isEqualToString:@"1"]) {
        [params setObject:_labelId forKey:@"labelId"];
    }else {
        [params setObject:_logId forKey:@"logId"];
    }
    [params setObject:_projectId forKey:@"projectId"];
    [iSeeNetworkRequest getWithHeaderUrl:[NSString stringWithFormat:@"%@%@", NMarketMainUrl, GetOrderListFroLot] params:params success:^(id object) {
        NSDictionary *body = object[@"body"];
        NSMutableArray *array = body[@"result"];
        if (array.count > 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            for (NSDictionary *tempDic in array) {
                [alert addAction:[UIAlertAction actionWithTitle:tempDic[@"pcName"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    self.batchSelection = tempDic[@"pcName"];
                    self.batchSelectionId = tempDic[@"pcId"];
                    [self.tableView.mj_header beginRefreshing];
                }]];
            }
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            
            [self presentViewController:alert animated:YES completion:nil];
            
        }else {
            [SVProgressHUD showErrorWithStatus:@"无批次可选"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
}

//全选
- (IBAction)selectAllButtonAction:(UIButton *)sender {
    
    if (_dataList.count == _selectedArray.count) {
        for (NewMissionListDetailModel *model in _dataList) {
            model.isSelect = NO;
        }
        [self.selectedArray removeAllObjects];
        [self setSelectButtomStatus];
        [self.tableView reloadData];
        
    }else {
        for (NewMissionListDetailModel *model in _dataList) {
            if (!model.isSelect) {
                model.isSelect = YES;
                [_selectedArray addObject:model];
            }
        }
        [self setSelectButtomStatus];
        [self.tableView reloadData];
    }
    
    
    
}

- (void)updownButtonAction:(UIButton *)button {
    ZSBSearchModel *tempModel = _searchModel.order.data[0];
    
    if ([_upDownModel.name isEqualToString:tempModel.name]) {
        _upDownModel = _searchModel.order.data[1];
    }else {
        _upDownModel = _searchModel.order.data[0];
    }
    [button setImage:[self getImageFromBundle:_upDownModel.name] forState:UIControlStateNormal];
    
    [_tableView.mj_header beginRefreshing];
}

- (void)tiemFilterViewAction:(UITapGestureRecognizer *) tap {
    
    CGRect rc = [tap.view convertRect:tap.view.bounds toView:self.view.window];
    
    CGPoint point = CGPointMake(rc.origin.x, rc.origin.y + rc.size.height);
    
    [NewLoveMarketTimeFilterView showNewLoveMarketTimeFilterView:self.view.window point:point timeFiterList:_timeFilterList success:^(NSDictionary *selectTime) {
        self.timeFilterDic = selectTime;
        
        self.timeFilterDic = selectTime;
        
        NSLog(@"%@", selectTime);
        
        
        [self.tableView.mj_header beginRefreshing];
    } failure:^{

    }];

}

- (void)sortViewAction:(UITapGestureRecognizer *) tap {
    
    [ZSBWordOrdorSearchConditionView showSearchPickerInView:self.view.window array:_searchModel.orderName.data success:^(ZSBSearchModel *successModel) {
        
        if (self.sortModel == successModel) {
            return ;
        }
        self.sortModel = successModel;
        self.upDownModel = self.searchModel.order.data[0];
        
        [self.tableView reloadData];

        [self.tableView.mj_header beginRefreshing];
        
    } failure:^{
        
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
